package com.carful.xigua.modules.common.security;


import com.carful.xigua.modules.common.config.SecurityConfig;
import com.carful.xigua.modules.common.util.SecurityContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * 角色权限验证
 *
 * @author Administrator
 * Date 2024/2/18 14:56
 * Description
 */
@Component("RolePermissionHandler")
@Slf4j
public class RolePermissionHandler implements PermissionHandler<String, Object> {

    @Autowired
    private SecurityContextUtils securityContextUtils;

    @Override
    public boolean isPre(String target, Object... args) {
        return target != null;
    }

    @Override
    public boolean isPost(Object returnObject, Object... args) {
        return true;
    }

    @Override
    public boolean preHandle(String target, Object... args) {
        if (!isPre(target, args)) {
            return false;
        }
        SecurityConfig.LoginUserDetails loginUserDetails = securityContextUtils.getLoginUserDetails();

        return loginUserDetails.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_admin") || a.getAuthority().matches(target));
    }

    @Override
    public boolean postHandle(Object returnObject, Object... args) {
        return false;
    }
}
